package kuang.juc.rw;


import java.util.HashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 独占锁（写锁）一次只能一个线程
 * 共享锁（读锁）一次可以多个线程
 * 读写锁
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCacheLock myCache = new MyCacheLock();
        for (int i = 1; i <=5 ; i++) {
            String finalI = i+"";
            new Thread(()->{
                myCache.write(finalI,finalI);
            },String.valueOf(i)).start();
        }

        for (int i = 1; i <=5 ; i++) {
            String finalI = i+"";
            new Thread(()->{
                myCache.read(finalI);
            },String.valueOf(i)).start();
        }
    }
}

//自定义缓存
class MyCacheLock{
    private volatile HashMap<String, String> map=new HashMap<>();

    ReentrantReadWriteLock readWriteLock=new ReentrantReadWriteLock();

    public void write(String key,String value){
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"开始写");
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写OK");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public void read(String key){
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"开始读");
            String s = map.get(key);
            System.out.println(Thread.currentThread().getName()+"读ok");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();
        }

    }
}


//自定义缓存
class MyCache{
    private volatile HashMap<String, String> map=new HashMap<>();


    public void write(String key,String value){
        System.out.println(Thread.currentThread().getName()+"开始写");
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"写OK");
    }

    public void read(String key){
        System.out.println(Thread.currentThread().getName()+"开始读");
        String s = map.get(key);
        System.out.println(Thread.currentThread().getName()+"读ok");
    }
}
